package net.oschina.kjtang.qywx.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import net.oschina.kjtang.qywx.api.entity.AccessToken;
import net.oschina.kjtang.qywx.api.service.AccessTokenService;
import net.oschina.kjtang.qywx.common.component.httpclient.HttpClientComponent;
import net.oschina.kjtang.qywx.common.component.httpclient.HttpResult;
import net.oschina.kjtang.qywx.common.constants.WxAPIConstants;
import net.oschina.kjtang.qywx.common.constants.WxParaConstants;
import net.oschina.kjtang.qywx.common.exception.RCodeException;
import net.oschina.kjtang.qywx.common.service.impl.BaseServiceImpl;
import net.oschina.kjtang.qywx.config.dao.SystemConfigDao;
import net.oschina.kjtang.qywx.config.entity.SystemConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by kaijun on 2017/12/2.
 */
@Service
public class AccessTokenServiceImpl extends BaseServiceImpl<AccessToken> implements AccessTokenService {

    @Autowired
    private SystemConfigDao systemConfigDao;

    @Autowired
    private HttpClientComponent httpClientComponent;

    /**
     *  获取token
     */
    @Override
    public AccessToken getAccessToken() throws RCodeException {
        AccessToken accessToken = null;
        JSONObject  jsonObject = null;
        try {
            SystemConfig systemConfig = new SystemConfig();
            systemConfig.setKey(WxParaConstants.WX_CORPID);
            SystemConfig corpIdConfig = systemConfigDao.get(systemConfig);
            systemConfig.setKey(WxParaConstants.WX_SECRET);
            SystemConfig secretConfig = systemConfigDao.get(systemConfig);
            HttpResult httpResult = httpClientComponent.doPost(WxAPIConstants.ACCESS_TOKEN_URL.replace(WxParaConstants.WX_CORPID, corpIdConfig.getValue()).replace(WxParaConstants.WX_SECRET, secretConfig.getValue()));
            if (httpResult.getStatus() == 200) {
                accessToken = new AccessToken();
                jsonObject = JSONObject.parseObject(httpResult.getData());
                accessToken.setAccessToken(jsonObject.getString("access_token"));
                accessToken.setExpiresIn(jsonObject.getIntValue("expires_in"));
                int errcode = jsonObject.getIntValue("errcode");
                String errmsg = jsonObject.getString("errmsg");
                if(errcode!=0){
                    throw new RCodeException(22323,new RuntimeException(errmsg));
                }
                logger.info("[ACCESSTOKEN]", "获取ACCESSTOKEN失败 errcode:{} errmsg:{}", new Object[]{errcode,errmsg});
                logger.info("[ACCESSTOKEN]", "获取ACCESSTOKEN成功:{}", new Object[]{accessToken});
            }
        }catch (Exception e){
            throw new RCodeException(22323,e);
        }
        return accessToken;
    }
}
